import re
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ

from apps.autho.utils import secret,secretOpen
from meiduo import settings
from django.http.response import JsonResponse, HttpResponseBadRequest
from utils.response_code import RETCODE
from apps.autho.models import AuthoUser
from django_redis import get_redis_connection
from apps.users.models import User


# 拼接qq登陆界面链接
class QQLogin(View):
    def get(self, request):
        qq = OAuthQQ(
                client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state='test'
            )
        login_url = qq.get_qq_url()
        return JsonResponse({'code': RETCODE.OK, 'errmsg':'ok', 'login_url': login_url})

    def post(self, request):
        pass


# 生成openid(QQ标识符)
# 实现qq用户用户注册登陆
class QQOpenid(View):
    def get(self, request):
        code = request.GET.get('code')
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            redirect_uri=settings.QQ_REDIRECT_URI,
            client_secret=settings.QQ_CLIENT_SECRET,
        )
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)

        try:
            AuthoUser.objects.get(openid=openid)
        except Exception as e:
            openid = secret(openid)
            return render(request, 'oauth_callback.html', {'openid': openid})
        else:
            user = AuthoUser.user
            login(request, user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', user.username, max_age=12*24*3600)
            return response

    def post(self, request):
        # 接受数据
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')

        # 校验用户数据格式
        if not all([mobile, password, sms_code, access_token]):
            return HttpResponseBadRequest('参数不全')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('手机号格式不对')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseBadRequest('密码错误')
        try:
            openid = secretOpen(access_token)
            openid = openid.get('openid')
        except Exception as e:
            return HttpResponseBadRequest('openid错误')

        con = get_redis_connection('code')
        msg_server = con.get('msg_%s'%mobile)
        if msg_server is None:
            return HttpResponseBadRequest('短信验证码已过期')
        if msg_server.decode() != sms_code:
            return HttpResponseBadRequest('短信验证码错误')

        # 往QQ用户表当中添加数据
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username = mobile,
                mobile=mobile,
                password=password
            )
        else:
            if not user.check_password(password):
                return HttpResponseBadRequest('密码错误')

        try:
            AuthoUser.objects.create(
                user=user,
                openid=openid
            )
        except Exception as e:
            return HttpResponseBadRequest('数据库错误')

        # 跳转到首页
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', mobile, 12 * 24 * 3600)
        return response